package com.joysuch.wwyt.api.alarmbluetooth.service.impl;

import com.google.gson.reflect.TypeToken;
import com.joysuch.wwyt.api.alarmbluetooth.dto.OpenApiAlarmBell;
import com.joysuch.wwyt.api.alarmbluetooth.dto.OpenApiResult;
import com.joysuch.wwyt.api.alarmbluetooth.dto.OpenApiToken;
import com.joysuch.wwyt.api.alarmbluetooth.service.ReceiveSubscribeWwytService;
import com.joysuch.wwyt.api.alarmbluetooth.utils.JsonUtil;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.util.GsonUtils;
import com.joysuch.wwyt.workflow.api.service.PersonTrajectoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 订阅消息处理service
 *
 * @author sumeiqi
 * 2021-4-25 09:37:43
 */
@Service
@Slf4j
public class ReceiveSubscribeWwytServiceImpl implements ReceiveSubscribeWwytService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private PersonTrajectoryService personTrajectory;

    @Override
    public OpenApiResult receiveSubscribe(Long tenentId, String orgCode, Integer type) {
        OpenApiResult<OpenApiAlarmBell> openApiResult = new OpenApiResult<>();
        try {
            String token = personTrajectory.getTokenFromCache(tenentId,orgCode);
            BaseConfig ipConfig = baseConfigService.findConfig(tenentId,orgCode, BaseConfigCodes.OPEN_SERVICE_SERVER_URL);
            BaseConfig macConfig = baseConfigService.findConfig(tenentId,orgCode,BaseConfigCodes.OPEN_SERVICE_ALARM_BLUETOOTH_MAC);
            BaseConfig buildIdConfig = baseConfigService.findConfig(tenentId,orgCode,BaseConfigCodes.LOCATE_CURRENT_BUILD_ID);
            BaseConfig alarmConfig = baseConfigService.findConfig(tenentId,orgCode,BaseConfigCodes.OPEN_SERVICE_ALARM_BLUETOOTH_BUILD_ID);

            if (ipConfig == null) {
                log.error("开放平台服务URL地址缺失，请核对配置");
                return OpenApiResult.wrapErrorResult(Status.API_OPEN_SERVICE_SERVER_URL_NOT_EXIST.getCode(), Status.API_OPEN_SERVICE_SERVER_URL_NOT_EXIST.getMsg());
            }
            if (buildIdConfig == null) {
                log.error("定位系统建筑ID配置缺失，请核对配置");
                return OpenApiResult.wrapErrorResult(Status.API_LOCATE_CURRENT_BUILD_ID_NOT_EXIST.getCode(), Status.API_LOCATE_CURRENT_BUILD_ID_NOT_EXIST.getMsg());
            }
            if (macConfig == null) {
                log.error("声光报警设备对应蓝牙网关的Mac配置缺失，请核对配置");
                return OpenApiResult.wrapErrorResult(Status.API_OPEN_SERVICE_ALARM_BLUETOOTH_MAC_NOT_EXIST.getCode(), Status.API_OPEN_SERVICE_ALARM_BLUETOOTH_MAC_NOT_EXIST.getMsg());
            }
            if (alarmConfig == null) {
                log.error("声光报警设备对应蓝牙网关的BuildId配置缺失，请核对配置");
                return OpenApiResult.wrapErrorResult(Status.API_OPEN_SERVICE_ALARM_BLUETOOTH_BUILD_ID_NOT_EXIST.getCode(), Status.API_OPEN_SERVICE_ALARM_BLUETOOTH_BUILD_ID_NOT_EXIST.getMsg());
            }
            if(!alarmConfig.getValue().equalsIgnoreCase(buildIdConfig.getValue())){
                log.error("定位系统建筑ID配置不一致，请核对配置");
                return OpenApiResult.wrapErrorResult(Status.API_LOCATE_CURRENT_BUILD_ID_INVALID.getCode(), Status.API_LOCATE_CURRENT_BUILD_ID_INVALID.getMsg());

            }

            String mac = macConfig.getValue();
            String openUrl = ipConfig.getValue();
            String buildId = alarmConfig.getValue();
            log.info("buildId={},serverUrl={},token={}, mac={}", buildId, ipConfig.getValue(), token, mac);
            Map<String, Object> map = new HashMap<>();
            map.put("buildId", buildId);
            map.put("mac", mac);
            map.put("voiceLightFlag", type);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(map, new HttpHeaders());
            ResponseEntity<String> exchange = restTemplate.exchange(openUrl + "/api/devices/alarmBellCtrlV2?accessToken=" + token, HttpMethod.POST, requestEntity, String.class);
             openApiResult = GsonUtils.fromJson(exchange.getBody(), new TypeToken<OpenApiResult<OpenApiResult>>() {
            }.getType());
            if (openApiResult != null && openApiResult.getErrorCode() == 0) {
                log.info("buildId:{},mac:{},type:{},调用开放平台蓝牙网关灯光设备控制接口完成", buildId, mac, type == 1 ? "开" : "关");
            } else {
                log.error("调用失败:{}", exchange.toString());
                try {
                    for (int i = 1; i <= 3; i++) {
                        TimeUnit.SECONDS.sleep(1);
                        log.error("开始第{}次重新调用", i);
                        exchange = restTemplate.exchange(openUrl + "/api/devices/alarmBellCtrlV2?accessToken=" + token, HttpMethod.POST, requestEntity, String.class);
                        openApiResult = JsonUtil.fromJsonForGson(exchange.getBody(), new TypeToken<OpenApiResult<OpenApiToken>>() {
                        }.getType());
                        if (openApiResult != null && openApiResult.getErrorCode() == 0) {
                            log.error("第{}次重新调用开放平台蓝牙网关灯光设备控制接口成功,buildId:{},mac:{},type:{}", i, buildId, mac, type == 1 ? "开" : "关");
                            break;
                        } else {
                            log.error("第{}次重新调用失败:{}", i, exchange.toString());
                        }
                    }
                } catch (Exception e) {
                    log.error("调用开放平台蓝牙网关灯光设备控制接口异常", e);

                }
            }
        }catch (Exception e){
            log.error("调用开放平台蓝牙网关灯光设备控制接口异常", e);
            return OpenApiResult.wrapErrorResult(Status.FAILED.getCode(),e.getMessage());
        }
        return openApiResult;
    }
}
